// 算法执行页面的JavaScript逻辑

document.addEventListener('DOMContentLoaded', function() {
    console.log('算法执行页面已加载');
    
    // 初始化控制按钮
    initControlButtons();
    
    // 定期检查算法状态
    setInterval(checkAlgorithmStatus, 5000); // 每5秒检查一次
});

// 初始化控制按钮
function initControlButtons() {
    const runBtn = document.getElementById('run-algorithm');
    const stopBtn = document.getElementById('stop-algorithm');
    
    runBtn.addEventListener('click', runAlgorithm);
    stopBtn.addEventListener('click', stopAlgorithm);
}

// 运行算法
async function runAlgorithm() {
    try {
        showExecutionStatus('正在启动算法...', 'running');
        toggleControlButtons(true);
        
        // 发送运行算法请求
        const response = await fetch(CONFIG.API_BASE_URL + '/run', {
            method: 'POST'
        });
        
        if (!response.ok) {
            throw new Error(`算法执行请求失败: ${response.status}`);
        }
        
        const result = await response.json();
        
        if (result.status === 'success') {
            showExecutionStatus('算法执行完成', 'completed');
            updateResultsSummary(result);
        } else {
            showExecutionStatus('算法执行失败: ' + result.message, 'error');
        }
    } catch (error) {
        console.error('算法执行失败:', error);
        showExecutionStatus('算法执行失败: ' + error.message, 'error');
    } finally {
        toggleControlButtons(false);
    }
}

// 停止算法
async function stopAlgorithm() {
    try {
        // 发送停止算法请求
        const response = await fetch(CONFIG.API_BASE_URL + '/control', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ action: 'stop' })
        });
        
        if (!response.ok) {
            throw new Error(`停止算法请求失败: ${response.status}`);
        }
        
        const result = await response.json();
        
        if (result.status === 'success') {
            showExecutionStatus('算法已停止', 'completed');
        } else {
            showExecutionStatus('停止算法失败: ' + result.message, 'error');
        }
    } catch (error) {
        console.error('停止算法失败:', error);
        showExecutionStatus('停止算法失败: ' + error.message, 'error');
    }
}

// 检查算法状态
async function checkAlgorithmStatus() {
    try {
        // 获取算法状态
        const response = await fetch(CONFIG.API_BASE_URL + '/status');
        
        if (!response.ok) {
            throw new Error(`获取算法状态失败: ${response.status}`);
        }
        
        const status = await response.json();
        updateAlgorithmStatus(status);
    } catch (error) {
        console.error('检查算法状态失败:', error);
    }
}

// 更新算法状态显示
function updateAlgorithmStatus(status) {
    document.getElementById('running-status').textContent = status.is_running ? '运行中' : '未运行';
    document.getElementById('execution-progress').textContent = status.progress + '%';
    document.getElementById('current-phase').textContent = status.message;
    
    // 根据运行状态更新按钮
    const runBtn = document.getElementById('run-algorithm');
    const stopBtn = document.getElementById('stop-algorithm');
    
    if (status.is_running) {
        runBtn.disabled = true;
        stopBtn.disabled = false;
        showExecutionStatus('算法运行中...', 'running');
    } else {
        runBtn.disabled = false;
        stopBtn.disabled = true;
    }
}

// 切换控制按钮状态
function toggleControlButtons(running) {
    const runBtn = document.getElementById('run-algorithm');
    const stopBtn = document.getElementById('stop-algorithm');
    
    if (running) {
        runBtn.disabled = true;
        stopBtn.disabled = false;
    } else {
        runBtn.disabled = false;
        stopBtn.disabled = true;
    }
}

// 显示执行状态
function showExecutionStatus(message, type) {
    const statusDiv = document.getElementById('execution-status');
    statusDiv.textContent = message;
    statusDiv.className = 'execution-status ' + type;
}

// 更新结果摘要
function updateResultsSummary(result) {
    const summaryDiv = document.getElementById('results-summary');
    
    if (result.results && result.results.summary) {
        const summary = result.results.summary;
        
        summaryDiv.innerHTML = `
            <table class="results-table">
                <tr>
                    <th>总货物数</th>
                    <td>${summary.total_shipments}</td>
                    <th>匹配货物数</th>
                    <td>${summary.matched_shipments}</td>
                </tr>
                <tr>
                    <th>总容量</th>
                    <td>${summary.total_capacity}</td>
                    <th>匹配容量</th>
                    <td>${summary.matched_capacity}</td>
                </tr>
                <tr>
                    <th>稳定性</th>
                    <td>${summary.stability ? '稳定' : '不稳定'}</td>
                    <th>执行时间</th>
                    <td>${summary.execution_time} 秒</td>
                </tr>
                <tr>
                    <th>迭代次数</th>
                    <td>${summary.iterations}</td>
                    <th>未匹配货物</th>
                    <td>${summary.unmatched_shipments}</td>
                </tr>
            </table>
        `;
    } else {
        summaryDiv.innerHTML = '<p>无法显示结果摘要</p>';
    }
}